package cn.xd.base.application.service.common.impl;

import cn.xd.base.application.assembler.KeyValueAssembler;
import cn.xd.base.application.service.common.KeyValueAppService;
import cn.xd.base.basic.constants.CacheConstants;
import cn.xd.base.basic.type.DictCode;
import cn.xd.base.basic.type.KeyValueKey;
import cn.xd.base.domain.bean.command.AddKeyValueCommand;
import cn.xd.base.domain.bean.command.DeleteKeyValueCommand;
import cn.xd.base.domain.bean.command.UpdateKeyValueCommand;
import cn.xd.base.domain.bean.response.KeyValueDTO;
import cn.xd.base.domain.entity.KeyValue;
import cn.xd.base.domain.repository.KeyValueRepository;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author : mirzaLin
 * @data : 2023/11/20
 * @description : 字典配置
 **/
@Service
public class KeyValueAppServiceImpl implements KeyValueAppService {
    @Resource
    private KeyValueRepository keyValueRepository;

    /**
     * 新增字典配置
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = CacheConstants.DICT_CACHE, key = "#command.getDictCode()+'*'")
    public KeyValueDTO addKeyValue(AddKeyValueCommand command, Long userId) {
        // 执行新增操作
        KeyValue add = KeyValue.add(command, userId);
        keyValueRepository.save(add);
        return KeyValueAssembler.INSTANCE.toDto(add);
    }


    /**
     * 修改字典配置
     *
     * @param command oldValue
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = CacheConstants.DICT_CACHE, key = "#command.getDictCode()+'*'")
    public void updateKeyValue(UpdateKeyValueCommand command, Long userId) {
        // 寻找对应的字典配置
        KeyValue keyValue = keyValueRepository.find(DictCode.of(command.getDictCode()), KeyValueKey.of(command.getOldDictKey())).isEmptyThrow("该类型原key值不存在");
        // 执行修改操作
        keyValue.update(command, userId);
        keyValueRepository.save(keyValue);
    }

    /**
     * 删除字典配置
     *
     * @param command type & value
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = CacheConstants.DICT_CACHE, key = "#command.getDictCode()+'*'")
    public void deleteKeyValue(DeleteKeyValueCommand command) {
        KeyValue keyValue = keyValueRepository.find(DictCode.of(command.getDictCode()), KeyValueKey.of(command.getDictKey())).isEmptyThrow("该类型Key值不存在");
        keyValueRepository.remove(keyValue);
    }
}
